﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Windows.Forms;
using PayexpDAL;
using Utilities;
using System.Globalization;
using ExcelHandler;

namespace Moneymatters
{
    /// <summary>
    /// 
    /// </summary>
    public partial class MainForm
    {
        #region Private Fields
        #endregion Private Fields

        #region Properties
        #endregion Properties

        #region Private Methods

        private void DisplayBankAccountDetails()
        {
            //DataAccessHandler dataAccessHandler = new DataAccessHandler();
            //List<BankAccount> bankAccountList = dataAccessHandler.GetAllBankAccounts(Utils.FinancialYear, MainForm.Context);

            //bankAccountList = new DataAccessHandler().SetBankBalances(bankAccountList, MainForm.Context);

            this.dataGridBankAccounts.Rows.Clear();
            //foreach (BankAccount bankAccount in bankAccountList)
            List<BankAccount> temp = new List<BankAccount>();
            temp.AddRange(SettingsAndStaticListLoader.BankAccountList);
            foreach (BankAccount bankAccount in temp)
            {
                this.dataGridBankAccounts.Rows.Add();
                int newRowIndex = this.dataGridBankAccounts.Rows.Count - 1;
                DataGridViewRow newRow = this.dataGridBankAccounts.Rows[newRowIndex];

                StaticList requiredBank = SettingsAndStaticListLoader.BankNameList.Where(t => t.ListItemCode.Equals(bankAccount.BankName)).FirstOrDefault();
                string requiredBankDisplayName = bankAccount.BankName;
                if (requiredBank != null)
                {
                    requiredBankDisplayName = requiredBank.ListItemValue;
                }

                newRow.Cells["bankName"].Value = requiredBankDisplayName;

                if (bankAccount.IsBankAccountActive)
                {
                    newRow.Cells["accountStatus"].Value = "Active";
                }
                else
                {
                    newRow.Cells["accountStatus"].Value = "Closed";
                }

                string bankDetails = string.Format("A/c No: {0}{1}IFSC: {2}{3}MICR Code: {4}",
                                                    bankAccount.AccountNumber,
                                                    Environment.NewLine,
                                                    bankAccount.IFSCCode,
                                                    Environment.NewLine,
                                                    bankAccount.MICRCode);
                newRow.Cells["bankDetails"].Value = bankDetails;



                newRow.Cells["fyStartEnd"].Value = bankAccount.FinancialYearStart.ToString() + "-" + bankAccount.FinancialYearEnd.ToString();

                newRow.Cells["openingBalance"].Value = bankAccount.FinancialYearOpeningBalance;

                if (bankAccount.LastReconciliationActivityDate.HasValue)
                {
                    newRow.Cells["lastReconciledOn"].Value = bankAccount.LastReconciliationActivityDate.Value.Get_DD_MONTH_YY_DateString();
                }
                else
                {
                    newRow.Cells["lastReconciledOn"].Value = "Not Reconciled";
                }

                if (bankAccount.LatestReconciledTransactionBankDate.HasValue)
                {
                    newRow.Cells["latestReconciledBankDate"].Value = bankAccount.LatestReconciledTransactionBankDate.Value.Get_DD_MONTH_YY_DateString();
                }
                else
                {
                    newRow.Cells["latestReconciledBankDate"].Value = "Not Reconciled";
                }



                newRow.Cells["reonciledBalance"].Value = bankAccount.ReonciledBalance; // compute current balance for this bank
                newRow.Cells["reonciledBalance"].Style.BackColor = Color.GreenYellow;
                newRow.Cells["availableBalance"].Value = bankAccount.AvailableBalance; // compute current balance for this bank


                if (bankAccount.NoOfUnreconciledExpenseTransactions.HasValue)
                {
                    newRow.Cells["numberOfUnreconciledExpenseRecords"].Value = bankAccount.NoOfUnreconciledExpenseTransactions.Value; // compute current balance for this bank
                }

                if (bankAccount.NoOfUnreconciledIncomeTransactions.HasValue)
                {
                    newRow.Cells["numberOfUnreconciledIncomeRecords"].Value = bankAccount.NoOfUnreconciledIncomeTransactions.Value; // compute current balance for this bank
                }


                newRow.Tag = bankAccount;

                //newRow.Cells["printReceiptVoucher"].Value = ""

                foreach (DataGridViewCell cell in newRow.Cells)
                {
                    cell.Style.WrapMode = DataGridViewTriState.True;
                }
            }

            this.labelForFinancialYear.Text = "For FY " + Utils.FinancialYear.FinancialYearStart.ToString() + "-" + Utils.FinancialYear.FinancialYearEnd.ToString();
            // TO DO
            //if (this.radioBtnBankDateFilter.Checked)
            //{
            //    this.comboBoxBankAccountsFilter.Visible = true;
            //}
            //else
            //{
            //    this.comboBoxBankAccountsFilter.Visible = false;
            //}

        }

        void dataGridBankAccounts_Click(object sender, EventArgs e)
        {
            DataGridView dataGridView = (DataGridView)sender;

            if (this.dataGridBankAccounts.SelectedRows.Count == 0)
            {
                buttonClearBankDetailsFields_Click(null, null);
                return;
            }

            DataGridViewRow selectedRow = dataGridView.SelectedRows[0]; // multi select not considered
            BankAccount bankAccount = (BankAccount)selectedRow.Tag;

            int index = 0;
            foreach (ComboBoxItem item in this.comboBoxBankNames.Items)
            {
                if (((StaticList)item.Value).ListItemCode.Equals(bankAccount.BankName))
                {
                    this.comboBoxBankNames.SelectedIndex = index;
                    break;
                }

                index++;
            }

            this.textBoxAccountNumber.Text = bankAccount.AccountNumber;
            this.textBoxIFSC.Text = bankAccount.IFSCCode;
            this.textBoxMICR.Text = bankAccount.MICRCode;


            this.textBoxOpeningBalance.Text = bankAccount.FinancialYearOpeningBalance.ToString();

            this.checkBoxCloseBankAccount.Checked = !bankAccount.IsBankAccountActive;
        }

        private void buttonAddBankDetails_Click(object sender, EventArgs e)
        {
            BankAccount bankAccount = null;
            if (this.dataGridBankAccounts.SelectedRows.Count != 0)
            {
                DataGridViewRow selectedRow = this.dataGridBankAccounts.SelectedRows[0];
                bankAccount = (BankAccount)selectedRow.Tag; ;
            }

            ComboBoxItem selectedItem = (ComboBoxItem)this.comboBoxBankNames.SelectedItem;
            StaticList staticList = (StaticList)selectedItem.Value;

            try
            {
                bankAccount = Translator.ToBankAccountDB(staticList.ListItemCode, this.textBoxAccountNumber.Text,
                                                      this.textBoxIFSC.Text, this.textBoxMICR.Text, this.textBoxOpeningBalance.Text,
                                                      !this.checkBoxCloseBankAccount.Checked, bankAccount);


                this.dataAccessHandlerCommonInstance.SaveBankAccount(bankAccount, MainForm.Context);
                LoadBankAccounts();
                MessageBox.Show("Your data was saved sucessfully", "Save successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ValidationException vex)
            {
                MessageBox.Show(string.Format("There was a problem saving your data. {0}", vex.Message), "Save failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (DALException dex)
            {
                MessageBox.Show(string.Format("There was a problem saving your data. {0}", dex.Message), "Save failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem saving your data. \r\n Please view the log file and share it with your administrator.", "Save failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

        }

        private void buttonClearBankDetailsFields_Click(object sender, EventArgs e)
        {
            this.textBoxAccountNumber.Clear();
            this.textBoxIFSC.Clear();
            this.textBoxMICR.Clear();
            this.textBoxOpeningBalance.Clear();
            this.checkBoxCloseBankAccount.Checked = false;
        }

        private void buttonExportBankStatement_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.dataGridBankAccounts.SelectedRows.Count == 0)
            {
                MessageBox.Show("Please select a bank before clicking 'Export Bank Statement'. Click the first cell in the row to select a bank for exporting its statement to an excel file.", "No Bank Selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Cursor = Cursors.Arrow;
                return;
            }

            DataGridViewRow selectedRow = this.dataGridBankAccounts.SelectedRows[0]; // multi select not considered
            BankAccount bankAccount = (BankAccount)selectedRow.Tag;

            try
            {
                string exportFileName = "BankStatement_" + bankAccount.BankDisplayName + "_" + DateTime.Now.GetFileTime() + ".xlsx";
                //exportFileName = Path.Combine(AppSettingsLoader.AppSettingsValuesMap[Constants.AppSettingsKeys.ExportedFilesLocation], exportFileName);
                exportFileName = Path.Combine(SettingsAndStaticListLoader.GetAppSettingValue(Constants.AppSettingsKeys.ExportedFilesLocation), exportFileName);
                BankStatementExportToExcel bankStatementExportToExcel = new BankStatementExportToExcel(exportFileName, true, bankAccount);
                //DataAccessHandler dataAccessHandler = new DataAccessHandler();
                int numberOfRecordsPerPage = 30;
                int pageNumber = 0;
                int numberOfRecordsReturned = numberOfRecordsPerPage;
                int totalNoOfRecords = 0;
                int currentProgress = 0;
                this.progressBarForBankStatementExport.Visible = true;
                this.progressBarForBankStatementExport.Value = currentProgress;

                bool recordsReturned = false;

                while (numberOfRecordsReturned == numberOfRecordsPerPage)
                {
                    List<TransactionMaster> filteredResult = this.dataAccessHandlerCommonInstance.GetReconciledBankRecords(bankAccount.Id, pageNumber, numberOfRecordsPerPage, out totalNoOfRecords, MainForm.Context);
                    if (filteredResult.Count == 0)
                    {
                        //MessageBox.Show("No records to export", "No records", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //this.Cursor = Cursors.Arrow;
                        //return;

                        break;
                    }

                    recordsReturned = true;

                    filteredResult = this.dataAccessHandlerCommonInstance.SetCurrentBalance(filteredResult, true, bankAccount.Id, MainForm.Context);

                    numberOfRecordsReturned = filteredResult.Count;
                    bankStatementExportToExcel.ExportInBatches(filteredResult);

                    int percentIncrease = (numberOfRecordsReturned * 100) / totalNoOfRecords;
                    currentProgress = currentProgress + percentIncrease;
                    if (currentProgress <= 100)
                    {
                        this.progressBarForBankStatementExport.Value = currentProgress;
                    }
                    else
                    {
                        this.progressBarForBankStatementExport.Value = 100;
                    }

                    pageNumber++;
                }

                if (!recordsReturned)
                {
                    MessageBox.Show("No records to export", "No records", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    bankStatementExportToExcel.CloseBatch();
                    this.progressBarForBankStatementExport.Value = 100;
                    Process.Start(exportFileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry, there was a problem trying to export the selected bank's statement to an excel file. Please try again. If the problem persists, please contact your administrator", "Error when exporting", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Cursor = Cursors.Arrow;
                return;
            }
            finally
            {
                this.progressBarForBankStatementExport.Visible = false;
                this.Cursor = Cursors.Arrow;
            }
        }

        #endregion Private Methods

        #region Public Methods
        #endregion Public Methods
    }
}